package com.dhcc.cdc.busi.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.dao.*;
import com.dhcc.cdc.busi.entity.*;
import com.dhcc.cdc.busi.service.ICdcDictionaryService;
import com.dhcc.cdc.busi.service.ICdcExaminationService;
import com.dhcc.cdc.sys.dao.CdcDataMapper;
import com.dhcc.cdc.sys.entity.CdcDataEntity;
import com.dhcc.cdc.sys.service.ICdcDataService;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.util.CommonUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 检查报告表数据服务层接口
 * 
 * @ClassName: CdcExaminationServiceImpl
 * @Description: TODO
 * @author jumper
 * @date 2021-03-15 10:20:08
 */
@Service("cdcExaminationService")
public class CdcExaminationServiceImpl extends BaseServiceImpl<CdcExaminateMapper, CdcExaminateEntity> implements ICdcExaminationService {
	@Autowired
	private CdcEpisodeMapper cdcEpisodeMapper;
	
	@Autowired
	private CdcDictypeMapper cdcDictypeMapper;
	
	@Autowired
    private CdcDictionaryMapper cdcDictionaryMapper;
	
	@Autowired
	private CdcOrdmastMapper cdcOrdmastMapper;
	
	@Autowired
	private CdcUserMapper cdcUserMapper;
	
	@Autowired
	private CdcDataMapper cdcDataMapper;
	
	@Autowired
	ICdcDictionaryService dictritionSrv;
	@Autowired
	ICdcDataService dataSrv;
	@Override
	public List<CdcExaminateEntity> page(Page<CdcExaminateEntity> page, Map<String, Object> map) {
		return warpExamination(this.baseMapper.page(page, map));
	}
	@Override
	public List<CdcExaminateEntity> list(Map<String, Object> map) {
		return this.baseMapper.list(map);
	}

	/**
	*by xzl
	*/
	public List<CdcExaminateEntity> warpExamination(List<CdcExaminateEntity> list){

		Map<Long, Object> cacheDic = new HashMap<Long, Object>();
		for(CdcExaminateEntity examination:list){
			if(examination.getBusExamReportStatusId()!=null){
				if(cacheDic.containsKey(examination.getBusExamReportStatusId())){
					examination.setBusExamReportStatus( (CdcDictionaryEntity) cacheDic.get(examination.getBusExamReportStatusId()));
				}else{
					CdcDictionaryEntity examStatus=this.dictritionSrv.selectById(examination.getBusExamReportStatusId());
					examination.setBusExamReportStatus(examStatus);
					cacheDic.put(examination.getBusExamReportStatusId(),examStatus);
				}
			}else{
				examination.setBusExamReportStatus(new CdcDictionaryEntity());
			}
			if(examination.getDataId()!=null){
				if(cacheDic.containsKey(examination.getDataId())){
					examination.setData((CdcDataEntity) cacheDic.get(examination.getDataId()));
				}else{
					CdcDataEntity data = this.dataSrv.selectById(examination.getDataId());
					examination.setData(data);
					cacheDic.put(examination.getDataId(), data);
				}
			}else{
				examination.setData(new CdcDataEntity());
			}
		}

		return list;
	}
	@Override
	public String handleXmlData(String dataStr) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Document doc = null;
        try {
            doc = DocumentHelper.parseText(dataStr); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            Iterator<Element> iter = rootElt.elementIterator("examinfo"); // 获取根节点下的子节点examinfo
            // 遍历emr节点
            while (iter.hasNext()) {
                Element examEle = iter.next();
                String xcode = examEle.elementTextTrim("xcode"); //索引码
                String episodeid = examEle.elementTextTrim("episodeid"); //就诊记录
                String examnum = examEle.elementTextTrim("examnum"); //检查号
                String bsordexecid = examEle.elementTextTrim("bsordexecid"); //医嘱
                String busexamreportstatuscode = examEle.elementTextTrim("busexamreportstatuscode"); //状态
                String busexamreportstatusdesc = examEle.elementTextTrim("busexamreportstatusdesc"); //状态
                String description = examEle.elementTextTrim("description"); //描述
                String examdesc = examEle.elementTextTrim("examdesc"); //检查所见
                String resultdesc = examEle.elementTextTrim("resultdesc"); //诊断意见
                String repusername = examEle.elementTextTrim("repusername"); //报告人
                String repdatestr = examEle.elementTextTrim("repdate"); //报告日期
                String regusername = examEle.elementTextTrim("regusername"); //登记人
                String regdatestr = examEle.elementTextTrim("regdate"); //登记日期
                String updatetimestr = examEle.elementTextTrim("updatetime"); //更新时间
                String updateuserid = examEle.elementTextTrim("updateuserid"); //更新人
                String opercode = examEle.elementTextTrim("opercode"); //操作码
                CdcExaminateEntity exam = new CdcExaminateEntity();
                exam.setXcode(xcode);
                //获取dataid
            	CdcDataEntity cdcDataEntity = new CdcDataEntity();
            	cdcDataEntity.setCode("EmrData");
            	cdcDataEntity.setIsActive(1);
            	cdcDataEntity = cdcDataMapper.selectOne(cdcDataEntity);
        		Long dataId = cdcDataEntity.getId();
        		//获取basedataId
    			CdcDataEntity cdcDataEntityBase = new CdcDataEntity();
    			cdcDataEntityBase.setCode("HisBase");
    			cdcDataEntityBase.setIsActive(1);
    			cdcDataEntityBase = cdcDataMapper.selectOne(cdcDataEntityBase);
        		Long basedataId = cdcDataEntityBase.getId();
        		//获取orddataId
    			CdcDataEntity cdcDataEntityOrd = new CdcDataEntity();
    			cdcDataEntityOrd.setCode("OrdData");
    			cdcDataEntityOrd.setIsActive(1);
    			cdcDataEntityOrd = cdcDataMapper.selectOne(cdcDataEntityOrd);
        		Long orddataId = cdcDataEntityOrd.getId();
                if(CommonUtil.isNotEmpty(updatetimestr)) {
            		Date updatetime = sdf.parse(updatetimestr);
            		exam.setUpdateDate(updatetime);
            	}
            	//获取更新人
            	if(CommonUtil.isNotEmpty(updateuserid)) {
            		CdcUserEntity cdcUserEntity = new CdcUserEntity();
            		cdcUserEntity.setXcode(updateuserid);
            		cdcUserEntity.setDataId(basedataId);
            		cdcUserEntity.setIsActive(1);
            		cdcUserEntity = cdcUserMapper.selectOne(cdcUserEntity);
            		//判断人员存在不存在
            		Long updateuser = null;
            		if(CommonUtil.isEmpty(cdcUserEntity)) {//不存在  保存到用户表里面
            			cdcUserEntity = new CdcUserEntity();
            			cdcUserEntity.setXcode(updateuserid);
                		cdcUserEntity.setIsActive(1);
            			cdcUserEntity.setCode("newuser"+updateuserid);
            			cdcUserEntity.setName("newuser"+updateuserid);
                		cdcUserEntity.setDataId(basedataId);
                		//保存用户
                		cdcUserMapper.insert(cdcUserEntity);
                		updateuser = cdcUserEntity.getId();
            		}else {
            			updateuser = cdcUserEntity.getId();
            		}
            		exam.setUpdateBy(updateuser);
            	}
                if("1".equals(opercode)) {//保存/修改
                	//获取episodeid
                	CdcEpisodeEntity cdcEpisodeEntity = new CdcEpisodeEntity();
                	cdcEpisodeEntity.setXcode(episodeid);
                	cdcEpisodeEntity=cdcEpisodeMapper.selectOne(cdcEpisodeEntity);//就诊信息没在库中？？？
                	Long epsid = cdcEpisodeEntity.getId();
                	exam.setEpisodeId(epsid);
                	//根据医嘱条目id获取longid
                	if(CommonUtil.isNotEmpty(bsordexecid)) {
                		//如果没有对应ID就要插入
                		CdcOrdmastEntity cdcOrdmastEntity = new CdcOrdmastEntity();
                		cdcOrdmastEntity.setXcode(bsordexecid);
                		cdcOrdmastEntity.setDataId(orddataId);
                		cdcOrdmastEntity.setIsActive(1);
                		cdcOrdmastEntity = cdcOrdmastMapper.selectOne(cdcOrdmastEntity);
                		if(CommonUtil.isNotEmpty(cdcOrdmastEntity)) {
                			Long orderid =cdcOrdmastEntity.getId();
                			exam.setBsOrdexecId(orderid);
                		}
                	}
                	//获取examstatusId
                	if(CommonUtil.isNotEmpty(busexamreportstatuscode)) {
                		CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
                    	cdcDictypeEntity.setCode("bus_exam_status");
                    	cdcDictypeEntity.setIsActive(1);
                    	cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
                		Long dicexamstatusId = cdcDictypeEntity.getId();
                		//如果没有对应ID就要插入
                		CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
                		cdcDictionaryEntity.setDictypeId(dicexamstatusId);
                		cdcDictionaryEntity.setCode(busexamreportstatuscode);
                		cdcDictionaryEntity.setIsActive(1);
                		cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
                		//判断字典存在不存在
                		Long busexamstatusid = null;
                		if(CommonUtil.isEmpty(cdcDictionaryEntity)) {//不存在  保存到字典表里面
                			cdcDictionaryEntity = new CdcDictionaryEntity();
                			cdcDictionaryEntity.setDictypeId(dicexamstatusId);
                			cdcDictionaryEntity.setCode(busexamreportstatuscode);
                			cdcDictionaryEntity.setDescription(busexamreportstatusdesc);
                			cdcDictionaryEntity.setIsActive(1);
                    		//保存字典
                			cdcDictionaryMapper.insert(cdcDictionaryEntity);
                			busexamstatusid = cdcDictionaryEntity.getId();
                		}else {
                			busexamstatusid = cdcDictionaryEntity.getId();
                		}
                		exam.setBusExamReportStatusId(busexamstatusid);
                	}
                	if(CommonUtil.isNotEmpty(examnum)) {
                		exam.setExamNum(examnum);
                	}
                	if(CommonUtil.isNotEmpty(epsid)) {
                		exam.setBusExamReportStatusId(epsid);
                	}
                	if(CommonUtil.isNotEmpty(description)) {
                		exam.setDescription(description);
                	}
                	if(CommonUtil.isNotEmpty(examdesc)) {
                		exam.setExamDesc(examdesc);
                	}
                	if(CommonUtil.isNotEmpty(resultdesc)) {
                		exam.setResultDesc(resultdesc);
                	}
                	if(CommonUtil.isNotEmpty(repusername)) {
                		exam.setRepUserName(repusername);
                	}
                	if(CommonUtil.isNotEmpty(repdatestr)) {
                		Date repdate = sdf.parse(repdatestr);
                		exam.setRepDate(repdate);
                	}
                	exam.setRegUserName(regusername);
                	if(CommonUtil.isNotEmpty(regdatestr)) {
                		Date regdate = sdf.parse(regdatestr);
                		exam.setRegDate(regdate);
                	}
                	exam.setDataId(dataId);
                	exam.setIsActive(1);
                }else {
                	exam.setIsActive(0);
                }
                //先判断是不是有该对象
                Wrapper<CdcExaminateEntity> wrapper =  new EntityWrapper<CdcExaminateEntity>();
                wrapper.eq("xcode", exam.getXcode());
                wrapper.eq("data_id", dataId);
                int count = this.selectCount(wrapper);
                if(count>0) {
                	this.update(exam, wrapper);
                }else {
                	this.insert(exam);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            return "<response><status>0</status><message>"+e.getMessage()+"</message></response>";
        } catch (Exception e) {
            e.printStackTrace();
            return "<response><status>0</status><message>"+e.getMessage()+"</message></response>";
        }
		return "<response><status>1</status><message>ok</message></response>";
	
	}

}